package org.example.service;

import org.example.dao.OrderDao;
import org.example.dao.ProductDao;
import org.example.pojo.Order;
import org.example.pojo.Product;

import java.util.List;

public class ProductService {
    private final ProductDao productDao = new ProductDao();
    private final OrderDao orderDao = new OrderDao();

    // 获取所有商品
    public List<Product> getAllProducts() {
        return productDao.getAllProducts();
    }

    // 添加商品
    public void addProduct(Product product) {
        if (product.getName() == null || product.getName().trim().isEmpty()) {
            throw new IllegalArgumentException("商品名称不能为空！");
        }
        if (product.getPrice() <= 0) {
            throw new IllegalArgumentException("商品价格必须大于0！");
        }
        productDao.addProduct(product);
    }

    // 删除商品
    public boolean deleteProduct(int productId) {
        Product product = productDao.getProductById(productId);
        if (product == null) {
            System.err.println("商品不存在，无法删除！");
            return false;
        }
        return productDao.deleteProduct(productId);
    }

    // 更新商品信息
    public void updateProduct(int productId, String name, double price, int stock) {
        Product product = new Product(productId, name, price, stock);
        productDao.updateProduct(product);
    }

    // 下单功能
    public boolean placeOrder(int userId, int productId, int quantity) {
        // 获取商品信息
        Product product = productDao.getProductById(productId);
        if (product == null) {
            System.err.println("商品不存在！");
            return false;
        }
        if (product.getStock() < quantity) {
            System.err.println("库存不足！");
            return false;
        }

        // 更新库存
        boolean isStockUpdated = productDao.updateStock(productId, product.getStock() - quantity);
        if (!isStockUpdated) {
            System.err.println("库存更新失败！");
            return false;
        }

        // 插入订单
        boolean isOrderInserted = orderDao.insertOrder(userId, productId, quantity);
        if (!isOrderInserted) {
            // 如果订单插入失败，回滚库存
            productDao.updateStock(productId, product.getStock());
            System.err.println("订单插入失败，库存扣减回滚！");
            return false;
        }

        return true;
    }

    // 恢复库存并删除订单
    public boolean restoreStockByOrder(int orderId) {
        // 获取订单详情
        Order order = orderDao.getOrderById(orderId);
        if (order == null) {
            System.err.println("订单不存在，无法恢复库存！");
            return false;
        }

        // 提取订单信息
        int productId = order.getProductId();
        int quantity = order.getQuantity();

        // 获取商品信息
        Product product = productDao.getProductById(productId);
        if (product == null) {
            System.err.println("商品不存在，无法恢复库存！");
            return false;
        }

        // 恢复库存
        boolean isStockUpdated = productDao.updateStock(productId, product.getStock() + quantity);
        if (!isStockUpdated) {
            System.err.println("恢复库存失败！");
            return false;
        }

        // 删除订单
        boolean isOrderDeleted = orderDao.deleteOrderById(orderId);
        if (!isOrderDeleted) {
            // 如果删除订单失败，回滚库存恢复
            productDao.updateStock(productId, product.getStock() - quantity);
            System.err.println("订单删除失败，库存恢复回滚！");
            return false;
        }

        return true;
    }

    // 获取商品详情
    public Product getProductById(int productId) {
        return productDao.getProductById(productId);
    }

    // 批量下单
    public boolean placeMultipleOrders(int userId, List<Order> orders) {
        for (Order order : orders) {
            boolean success = placeOrder(userId, order.getProductId(), order.getQuantity());
            if (!success) {
                System.err.println("批量下单失败，回滚所有订单！");
                rollbackOrders(userId, orders);
                return false;
            }
        }
        return true;
    }

    // 回滚批量订单
    private void rollbackOrders(int userId, List<Order> orders) {
        for (Order order : orders) {
            restoreStockByOrder(order.getId());
        }
    }

    // 查询订单是否与商品有关联
    public boolean isProductInOrders(int productId) {
        List<Order> orders = orderDao.getOrdersByProductId(productId);
        return orders != null && !orders.isEmpty();
    }
}
